package com.example.springboot.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.example.springboot.controller.request.BaseRequest;
import com.example.springboot.entity.Book;
import com.example.springboot.exception.ServiceException;
import com.example.springboot.mapper.BookMapper;
import com.example.springboot.service.IBook;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class BookService implements IBook {

    @Resource
    BookMapper bookMapper;

    //查询所有
    @Override
    public List<Book> list() {
        return bookMapper.list();
    }

    //分页
    @Override
    public PageInfo<Book> page(BaseRequest baseRequest) {
        PageHelper.startPage(baseRequest.getPageNum(), baseRequest.getPageSize());
        List<Book> books = bookMapper.listByCondition(baseRequest);
        return new PageInfo<>(books);
    }

    //更新
    @Override
    public void update(Book book) {
        Date date = new Date();
        book.setUpdateTime(date);
        try {
        book.setCategory(setCategory(book.getCategories()));
        bookMapper.update(book);
        }catch (Exception e){
            throw  new ServiceException("数据更新异常", e);
        }
    }


    //新增
    @Override
    public void save(Book book) {
        Date date = new Date();
        book.setUpdateTime(date);
        try {
            book.setCategory(setCategory(book.getCategories()));
            bookMapper.save(book);
        }catch (Exception e){
            throw  new ServiceException("数据插入错误", e);
        }
    }

    private String setCategory(List<String> categories){
        StringBuilder sb = new StringBuilder();
        if (CollUtil.isNotEmpty(categories)){
            categories.forEach(v ->sb.append(v).append(">"));
            return sb.substring(0,sb.lastIndexOf(">"));
        }
        return sb.toString();
    }

    @Override
    public Book getById(Integer id) {
        return bookMapper.getById(id);
    }

    //删除
    @Override
    public void deleteById(Integer id) {
        bookMapper.deleteById(id);
    }

    @Override
    public Integer deleteByIds(List<Integer> ids) {
        return bookMapper.deleteByIds(ids);
    }


}
